import axios from 'axios'
export default {
  namespaced: true,
  state () {
    return {
      list: []
    }
  },
  getters: {
    sumPrice (state) {
      return state.list.filter((item) => item.checked).reduce((sum, item) => sum + item.price * item.num, 0)
    }
  },
  mutations: {
    setList (state, payload) {
      state.list = payload
    },
    setCount (state, payload) {
      const goods = state.list.find((item, index) => index === payload.id)
      goods.num = payload.count
    },
    delItem (state, payload) {
      state.list = state.list.filter((item, index) => index !== payload.id)
    },
    isAllChecked (state, payload) {
      return state.list.forEach(item => { item.checked = payload })
    },
    UpDateChecked (state, payload) {
      const goods = state.list.find((item, index) => index === payload.id)
      goods.checked = !goods.checked
    }

  },
  actions: {
    // 获取
    async getList ({ commit }) {
      const { data } = await axios.get('http://localhost:3000/goodList')
      commit('setList', data)
    },
    // 加减
    async updateCount ({ commit }, payload) {
      console.log(payload)
      await axios.get('http://localhost:3000/goodList', {
        num: payload.count
      })
      commit('setCount', payload)
    },
    // 删除
    async delItemData ({ commit }, payload) {
      await axios.get('http://localhost:3000/goodList')
      commit('delItem', payload)
    },
    async UpDateChecked ({ commit }, payload) {
      await axios.get('http://localhost:3000/goodList')
      commit('UpDateChecked', payload)
    },
    async isAllChecked ({ commit }, payload) {
      await axios.get('http://localhost:3000/goodList')
      commit('isAllChecked', payload)
    }
  }
}
